package webgoat.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;


/**
 * Mysql数据库连接工具类
 *
 * @auth Administrator
 * @date 2019-11-16 11:19
 * druid连接池
 */

@Component
public class SqlConnection1 {
    private static DruidDataSource dataSource; // druid数据源

    // druid数据源初始化
    static {
        InputStream is = SqlConnection1.class.getClassLoader().getResourceAsStream("druid.properties");
        Properties pro = new Properties();

        try {
            pro.load(is);
        } catch (Exception e) {
            e.printStackTrace();

        }
        dataSource = new DruidDataSource();
        dataSource.setDriverClassName(pro.getProperty("driverClassName"));
        dataSource.setUrl(pro.getProperty("url"));
        dataSource.setUsername(pro.getProperty("username"));
        dataSource.setPassword(pro.getProperty("password"));
    }

    /**
     * 获取数据源
     *
     * @return
     */
    public static DataSource getDataSource() {
        return dataSource;
    }

    /**
     * 获取数据库连接
     *
     * @return
     */
    public static Connection getConnection() {

        Connection conn = null;
        try {
            conn = dataSource.getConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 释放资源
     *
     * @param conn
     * @param st
     * @param rs
     */
    public static void close(Connection conn, Statement st, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (st != null) {
            try {
                st.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 释放资源
     *
     * @param conn
     * @param st
     */
    public static void close(Connection conn, Statement st) {
        close(conn, st, null);
    }




    public static void show() {
        System.out.println(dataSource);
    }
}
